package com.dm.interceptors;

import com.alibaba.fastjson.JSON;
import com.dm.exceptions.BasicException;
import com.dm.exceptions.ExceptionEnum;
import com.dm.vo.LoginUserVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author DongJunJun
 * @Date 2022/9/9 0:59
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {


    private RedisTemplate<String, String> redisTemplate;


    private static ThreadLocal<LoginUserVo> threadLocal = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断token
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            throw new BasicException(ExceptionEnum.USER_NONE_LOGIN);
        }
        //从redis中验证token是否过了有效期
        String s ;
        try {
            s = redisTemplate.opsForValue().get(token);
        } catch (Exception e) {
            throw new BasicException(ExceptionEnum.MAIL_SEND_ERROR);
        }
        if (StringUtils.isEmpty(s)) {
            throw new BasicException(ExceptionEnum.USER_NONE_LOGIN);
        }
        LoginUserVo loginUserVo = JSON.parseObject(s, LoginUserVo.class);
        threadLocal.set(loginUserVo);
        return true;
    }


    @Override
    public  void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       //请求结束后删除
        threadLocal.remove();
    }

    /**
     * 获取该线程携带的user对象
     * @return
     */
    public static LoginUserVo getLoginUserVo(){
       return threadLocal.get();
    }

    public LoginInterceptor(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
}
